package com.pzr.soccer.match.dao.impl;


import com.pzr.soccer.common.consts.RedisConst;
import com.pzr.soccer.match.dao.GameRepositoryHelper;
import com.pzr.soccer.match.domain.Game;
import com.pzr.soccer.match.model.request.DateLT;
import com.pzr.soccer.match.model.GameWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoOperations;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.redis.core.RedisTemplate;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Set;

/**
 * @Author pzr
 * @date:2021-12-15-17:36
 * @Description:
 **/
public class GameRepositoryImpl implements GameRepositoryHelper {
    @Autowired
    RedisTemplate<String ,Object> redisTemplate;
    @Autowired
    MongoOperations operations;
    @Override
    public List<GameWrapper> findOnGoingGamesInRedis() {
        return getGameWrappers(GameWrapper.Game_Cycle_Going);
    }

    @Override
    public List<GameWrapper> findComingGamesInRedis() {
        return getGameWrappers(GameWrapper.Game_Cycle_NotStartYet);

    }

    @Override
    public List<GameWrapper> findEndedGamesInRedis() {
        return getGameWrappers(GameWrapper.Game_Cycle_ended);
    }

    @Override
    public List<Game> findByDateLT(DateLT dlt) {
        Criteria criteria = Criteria.where("kickOff").gte(dlt.getBegin()).lte(dlt.getEnd());
        if (!dlt.getLeagues().isEmpty()) {
            criteria.and("联赛").in(dlt.getLeagues());
        }
        // 主队或者客队符合
        if (!dlt.getTeams().isEmpty()) {
            Criteria criteria_or=new Criteria();
            criteria.andOperator(criteria_or.orOperator(Criteria.where("主队").in(dlt.getTeams()),Criteria.where("客队").in(dlt.getTeams())));
        }
       return operations.find(Query.query(criteria),Game.class);
    }

    protected List<GameWrapper> getGameWrappers(int cycleStatus) {
        List<GameWrapper> wrappers=new ArrayList<>();
        Set<String> keys=redisTemplate.keys(RedisConst.Game_Today_Prefix+"*");
        for(String key: Objects.requireNonNull(keys)){
            GameWrapper wrapper= (GameWrapper) redisTemplate.opsForValue().get(key);
            if(wrapper!=null&&wrapper.getGameCycle()== cycleStatus){
                wrappers.add(wrapper);
            }
        }
        return wrappers;
    }
}
